package com.gitee.cui.basic.plus;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * 线程自增操作测试类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/18 16:57
 **/
@Slf4j
public class PlusTest {

    /**
     * 最大并发线程数
     */
    private static final int MAX_THREAD = 10;

    /**
     * 每个线程自增次数
     */
    private static final int MAX_TURN = 1000;

    /**
     * 倒数闩，等待10个线程的并发操作完成再接着往下运行
     */
    private CountDownLatch latch = new CountDownLatch(MAX_THREAD);

    @Test
    public void notSafePlusTest() throws InterruptedException {
        NotSafePlus notSafePlus = new NotSafePlus();
        Runnable runnable = () -> {
            for (int i = 0; i < MAX_TURN; i++) {
                notSafePlus.selfPlus();
            }
            latch.countDown();
        };

        for (int i = 0; i < MAX_THREAD; i++) {
            new Thread(runnable).start();
        }

        // 等待多线程并发操作完成
        latch.await();
        log.info("理论结果：{}", MAX_THREAD * MAX_TURN);
        log.info("实际结果：{}", notSafePlus.getAmount());
        log.info("差值：{}", (MAX_THREAD * MAX_TURN - notSafePlus.getAmount()));
    }

    @Test
    public void safePlusTest() throws InterruptedException {
        SafePlus safePlus = new SafePlus();
        Runnable runnable = () -> {
            for (int i = 0; i < MAX_TURN; i++) {
                safePlus.selfPlus();
            }
            latch.countDown();
        };

        for (int i = 0; i < MAX_THREAD; i++) {
            new Thread(runnable).start();
        }

        // 等待多线程并发操作完成
        latch.await();
        log.info("理论结果：{}", MAX_THREAD * MAX_TURN);
        log.info("实际结果：{}", safePlus.getAmount());
        log.info("差值：{}", (MAX_THREAD * MAX_TURN - safePlus.getAmount()));
    }
}
